import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Avatar,
  Tooltip,
  Modal,
  message,
  Popconfirm,
  Row,
  Col,
  Statistic,
  Badge,
  Typography
} from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  StopOutlined,
  PlayCircleOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ShopService } from '../../services/shopService';
import { Shop } from '../../types';

const { Search } = Input;
const { Option } = Select;
const { Title } = Typography;

interface ShopListState {
  shops: Shop[];
  loading: boolean;
  total: number;
  current: number;
  pageSize: number;
  keyword: string;
  status: string;
  type: string;
  selectedRowKeys: React.Key[];
}

const ShopList: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const [state, setState] = useState<ShopListState>({
    shops: [],
    loading: false,
    total: 0,
    current: 1,
    pageSize: 10,
    keyword: '',
    status: '',
    type: '',
    selectedRowKeys: [],
  });

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '商店管理' },
    ]));
    loadShops();
  }, [dispatch]);

  const loadShops = async (params?: Partial<ShopListState>) => {
    try {
      setState(prev => ({ ...prev, loading: true }));

      const queryParams = {
        page: params?.current || state.current,
        limit: params?.pageSize || state.pageSize,
        keyword: params?.keyword || state.keyword,
        status: params?.status || state.status,
        type: params?.type || state.type,
      };

      const response = await ShopService.getShops(queryParams);

      setState(prev => ({
        ...prev,
        shops: response.data || [],
        total: response.total || 0,
        current: response.page || 1,
        pageSize: response.limit || 10,
        loading: false,
      }));
    } catch (error) {
      console.error('加载商店列表失败:', error);
      message.error('加载商店列表失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  const handleSearch = (value: string) => {
    setState(prev => ({ ...prev, keyword: value, current: 1 }));
    loadShops({ keyword: value, current: 1 });
  };

  const handleStatusChange = (status: string) => {
    setState(prev => ({ ...prev, status, current: 1 }));
    loadShops({ status, current: 1 });
  };

  const handleTypeChange = (type: string) => {
    setState(prev => ({ ...prev, type, current: 1 }));
    loadShops({ type, current: 1 });
  };

  const handleTableChange: TableProps<Shop>['onChange'] = (pagination) => {
    const current = pagination?.current || 1;
    const pageSize = pagination?.pageSize || 10;
    setState(prev => ({ ...prev, current, pageSize }));
    loadShops({ current, pageSize });
  };

  const handleApprove = async (id: string) => {
    try {
      await ShopService.approveShop(id, { status: 'approved' });
      message.success('商店审核通过');
      loadShops();
    } catch (error) {
      message.error('审核失败');
    }
  };

  const handleReject = async (id: string) => {
    try {
      await ShopService.approveShop(id, { status: 'rejected', reason: '不符合要求' });
      message.success('商店审核拒绝');
      loadShops();
    } catch (error) {
      message.error('审核失败');
    }
  };

  const handleSuspend = async (id: string) => {
    try {
      await ShopService.suspendShop(id, '违规操作');
      message.success('商店已暂停');
      loadShops();
    } catch (error) {
      message.error('暂停失败');
    }
  };

  const handleResume = async (id: string) => {
    try {
      await ShopService.resumeShop(id);
      message.success('商店已恢复');
      loadShops();
    } catch (error) {
      message.error('恢复失败');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await ShopService.deleteShop(id);
      message.success('商店删除成功');
      loadShops();
      // 清空选中项
      setState(prev => ({ ...prev, selectedRowKeys: [] }));
    } catch (error: any) {
      console.error('删除失败:', error);

      // 获取错误信息
      let errorMessage = '删除失败';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.message) {
        errorMessage = error.message;
      }

      // 如果是因为有商品而无法删除，提供更详细的提示
      if (errorMessage.includes('商品')) {
        Modal.confirm({
          title: '无法删除商店',
          content: (
            <div>
              <p>{errorMessage}</p>
              <p>您可以选择：</p>
              <ul>
                <li>先删除该商店的所有商品，然后再删除商店</li>
                <li>或者将商店状态设置为"暂停"而不是删除</li>
              </ul>
            </div>
          ),
          okText: '查看商店商品',
          cancelText: '取消',
          onOk: () => {
            // 跳转到商店详情页面查看商品
            navigate(`/shops/${id}`);
          }
        });
      } else {
        message.error(errorMessage);
      }
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (state.selectedRowKeys.length === 0) {
      message.warning('请选择要删除的商店');
      return;
    }

    Modal.confirm({
      title: '批量删除商店',
      content: `确定要删除选中的 ${state.selectedRowKeys.length} 个商店吗？删除后无法恢复。`,
      okText: '确定删除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          // 将selectedRowKeys转换为字符串数组
          const ids = state.selectedRowKeys.map(key => key.toString());
          await ShopService.batchActionShops(ids, 'delete');
          message.success(`成功删除 ${ids.length} 个商店`);
          loadShops();
          setState(prev => ({ ...prev, selectedRowKeys: [] }));
        } catch (error: any) {
          console.error('批量删除失败:', error);

          let errorMessage = '批量删除失败';
          if (error?.response?.data?.message) {
            errorMessage = error.response.data.message;
          } else if (error?.message) {
            errorMessage = error.message;
          }

          // 如果是因为有商品而无法删除，提供更详细的提示
          if (errorMessage.includes('商品')) {
            Modal.error({
              title: '批量删除失败',
              content: (
                <div>
                  <p>{errorMessage}</p>
                  <p>部分商店可能包含商品，无法删除。请先删除这些商店中的所有商品，然后再尝试删除商店。</p>
                </div>
              ),
            });
          } else {
            message.error(errorMessage);
          }
        }
      }
    });
  };

  // 批量审核通过
  const handleBatchApprove = async () => {
    if (state.selectedRowKeys.length === 0) {
      message.warning('请选择要审核的商店');
      return;
    }

    Modal.confirm({
      title: '批量审核通过',
      content: `确定要审核通过选中的 ${state.selectedRowKeys.length} 个商店吗？`,
      okText: '确定通过',
      cancelText: '取消',
      onOk: async () => {
        try {
          const ids = state.selectedRowKeys.map(key => key.toString());
          await ShopService.batchActionShops(ids, 'approve');
          message.success(`成功审核通过 ${ids.length} 个商店`);
          loadShops();
          setState(prev => ({ ...prev, selectedRowKeys: [] }));
        } catch (error) {
          message.error('批量审核失败');
          console.error('批量审核失败:', error);
        }
      }
    });
  };

  // 批量暂停
  const handleBatchSuspend = async () => {
    if (state.selectedRowKeys.length === 0) {
      message.warning('请选择要暂停的商店');
      return;
    }

    Modal.confirm({
      title: '批量暂停商店',
      content: `确定要暂停选中的 ${state.selectedRowKeys.length} 个商店吗？`,
      okText: '确定暂停',
      cancelText: '取消',
      onOk: async () => {
        try {
          const ids = state.selectedRowKeys.map(key => key.toString());
          await ShopService.batchActionShops(ids, 'suspend', { reason: '批量操作暂停' });
          message.success(`成功暂停 ${ids.length} 个商店`);
          loadShops();
          setState(prev => ({ ...prev, selectedRowKeys: [] }));
        } catch (error) {
          message.error('批量暂停失败');
          console.error('批量暂停失败:', error);
        }
      }
    });
  };

  const getStatusTag = (status: string) => {
    const statusConfig = {
      active: { color: 'green', text: '正常' },
      pending: { color: 'orange', text: '待审核' },
      suspended: { color: 'red', text: '已暂停' },
      inactive: { color: 'gray', text: '已停用' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'gray', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getTypeTag = (type: string) => {
    const typeConfig = {
      official: { color: 'blue', text: '官方' },
      flagship: { color: 'purple', text: '旗舰' },
      authorized: { color: 'green', text: '授权' },
      personal: { color: 'default', text: '个人' },
    };
    const config = typeConfig[type as keyof typeof typeConfig] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns: ColumnsType<Shop> = [
    {
      title: '商店信息',
      key: 'info',
      width: 300,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar src={record.logo} size={48} style={{ marginRight: 12 }} />
          <div>
            <div style={{ fontWeight: 'bold', marginBottom: 4 }}>{record.name}</div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              店主: {record.owner?.name || 'N/A'}
            </div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              {record.categories?.join(', ') || 'N/A'}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type) => getTypeTag(type),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => getStatusTag(status),
    },
    {
      title: '评分',
      key: 'rating',
      width: 80,
      render: (_, record) => (
        <div>
          <div>{typeof record.rating === 'number' ? record.rating.toFixed(1) : (parseFloat(record.rating) || 0).toFixed(1)}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.reviewCount || 0} 评价
          </div>
        </div>
      ),
    },
    {
      title: '商品数',
      key: 'products',
      width: 80,
      render: (_, record) => record.stats?.totalProducts || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/shops/${record._id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => navigate(`/shops/${record._id}/edit`)}
            />
          </Tooltip>
          {record.status === 'pending' && (
            <>
              <Tooltip title="审核通过">
                <Button
                  type="text"
                  icon={<CheckOutlined />}
                  style={{ color: 'green' }}
                  onClick={() => handleApprove(record._id)}
                />
              </Tooltip>
              <Tooltip title="审核拒绝">
                <Button
                  type="text"
                  icon={<CloseOutlined />}
                  style={{ color: 'red' }}
                  onClick={() => handleReject(record._id)}
                />
              </Tooltip>
            </>
          )}
          {record.status === 'active' && (
            <Tooltip title="暂停">
              <Button
                type="text"
                icon={<StopOutlined />}
                style={{ color: 'orange' }}
                onClick={() => handleSuspend(record._id)}
              />
            </Tooltip>
          )}
          {record.status === 'suspended' && (
            <Tooltip title="恢复">
              <Button
                type="text"
                icon={<PlayCircleOutlined />}
                style={{ color: 'green' }}
                onClick={() => handleResume(record._id)}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个商店吗？"
            description={`删除后无法恢复，商店"${record.name}"的所有数据将被永久删除。`}
            onConfirm={() => handleDelete(record._id)}
            okText="确定删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Tooltip title="删除">
              <Button
                type="text"
                icon={<DeleteOutlined />}
                style={{ color: 'red' }}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>店铺列表</Title>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总商店数"
              value={state.total}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待审核"
              value={state.shops.filter(s => s.status === 'pending').length}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="正常营业"
              value={state.shops.filter(s => s.status === 'active').length}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已暂停"
              value={state.shops.filter(s => s.status === 'suspended').length}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card>
        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search
              placeholder="搜索商店名称、描述..."
              allowClear
              onSearch={handleSearch}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="状态筛选"
              allowClear
              style={{ width: '100%' }}
              onChange={handleStatusChange}
            >
              <Option value="active">正常</Option>
              <Option value="pending">待审核</Option>
              <Option value="suspended">已暂停</Option>
              <Option value="inactive">已停用</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="类型筛选"
              allowClear
              style={{ width: '100%' }}
              onChange={handleTypeChange}
            >
              <Option value="official">官方</Option>
              <Option value="flagship">旗舰</Option>
              <Option value="authorized">授权</Option>
              <Option value="personal">个人</Option>
            </Select>
          </Col>
          <Col span={8}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => navigate('/shops/create')}
              >
                新增商店
              </Button>
              <Button icon={<ExportOutlined />}>
                导出数据
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 批量操作栏 */}
        {state.selectedRowKeys.length > 0 && (
          <Row style={{ marginBottom: 16, padding: '12px', backgroundColor: '#f0f2f5', borderRadius: '6px' }}>
            <Col span={24}>
              <Space>
                <Text>已选择 {state.selectedRowKeys.length} 项</Text>
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  onClick={handleBatchApprove}
                >
                  批量审核通过
                </Button>
                <Button
                  icon={<StopOutlined />}
                  onClick={handleBatchSuspend}
                >
                  批量暂停
                </Button>
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  onClick={handleBatchDelete}
                >
                  批量删除
                </Button>
                <Button
                  type="link"
                  onClick={() => setState(prev => ({ ...prev, selectedRowKeys: [] }))}
                >
                  取消选择
                </Button>
              </Space>
            </Col>
          </Row>
        )}

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={state.shops}
          rowKey="_id"
          loading={state.loading}
          pagination={{
            current: state.current,
            pageSize: state.pageSize,
            total: state.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
          rowSelection={{
            selectedRowKeys: state.selectedRowKeys,
            onChange: (selectedRowKeys) => {
              setState(prev => ({ ...prev, selectedRowKeys }));
            }
          }}
        />
      </Card>
    </div >
  );
};

export default ShopList;
